package com.sf.kits.net;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;

import javax.net.ssl.*;


public class HttpsRequestUtil {
    private static class TrustAnyTrustManager implements X509TrustManager {
    
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }
    
    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
    
    /**
     * http请求
     * @param url
     * @param data
     * @return
     * @throws IOException 
     */
    public static String requestUrl(String url, HashMap<String, String> data)
            throws IOException {

        HttpURLConnection conn;
        try {
            //if GET....
            //URL requestUrl = new URL(url + "?" + httpBuildQuery(data));
            URL requestUrl = new URL(url);
            conn = (HttpURLConnection) requestUrl.openConnection();
        } catch (MalformedURLException e) {
            return e.getMessage();
        }

        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        conn.setDoInput(true);
        conn.setDoOutput(true);

        PrintWriter writer = new PrintWriter(conn.getOutputStream());
        writer.print(httpBuildQuery(data));
        writer.flush();
        writer.close();

        String line;
        BufferedReader bufferedReader;
        StringBuilder sb = new StringBuilder();
        InputStreamReader streamReader = null;
        try {
            streamReader = new InputStreamReader(conn.getInputStream(), "UTF-8");
        } catch (IOException e) {
            /*
            Boolean ret2 = true;
            if (ret2) {
                return e.getMessage();
            }
            */
            streamReader = new InputStreamReader(conn.getErrorStream(), "UTF-8");
        } finally {
            if (streamReader != null) {
                bufferedReader = new BufferedReader(streamReader);
                sb = new StringBuilder();
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                }
            }
        }
        return sb.toString();
    }
    
    /**
     * 参数编码
     * @param data
     * @return 
     */
    public static String httpBuildQuery(HashMap<String, String> data) {
        String ret = "";
        String k, v;
        Iterator<String> iterator = data.keySet().iterator();
        while (iterator.hasNext()) {
            k = iterator.next();
            v = data.get(k);
            try {
                ret += URLEncoder.encode(k, "utf8") + "=" + URLEncoder.encode(v, "utf8");
            } catch (UnsupportedEncodingException e) {
            }
            ret += "&";
        }
        return ret.substring(0, ret.length() - 1);
    }
    

    public static String sendHTTPSGet(String url,HashMap<String, String> data) throws Exception {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
        URL console = new URL(url);
        HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
        conn.setSSLSocketFactory(sc.getSocketFactory());
        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
       // conn.connect();
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        conn.setDoInput(true);
        conn.setDoOutput(true);

        PrintWriter writer = new PrintWriter(conn.getOutputStream());
        writer.print(httpBuildQuery(data));
        writer.flush();
        writer.close();

        String line;
        BufferedReader bufferedReader;
        StringBuilder sb = new StringBuilder();
        InputStreamReader streamReader = null;
        try {
            streamReader = new InputStreamReader(conn.getInputStream(), "UTF-8");
        } catch (IOException e) {
            /*
            Boolean ret2 = true;
            if (ret2) {
                return e.getMessage();
            }
            */
            streamReader = new InputStreamReader(conn.getErrorStream(), "UTF-8");
        } finally {
            if (streamReader != null) {
                bufferedReader = new BufferedReader(streamReader);
                sb = new StringBuilder();
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                }
            }
        }
        return sb.toString();
    }
}